<template>
  <div class="two-container">
    <div class="two-info-container">
      <div class="info-container">

        <div class="info-search">
          <el-icon>
            <Search/>
          </el-icon>
          <el-input
              v-model="search"
              placeholder="搜索"
              clearable
              @clear="search = ''"/>
        </div>
        <div class="info-table">
          <el-table

              :data="vehicles"
              scrollbar-always-on
              style="width: 100%;height: 360px;"
              @row-click="handleVehicleClick"
              :cell-style="{
          textAlign: 'center',
          cursor: 'pointer',
        }"
              :header-cell-style="{
          fontWeight: 'bold',
          textAlign: 'center',
        }"
              :row-class-name="tableRowClassName"
          >
            <el-table-column
                prop="vehicleNo"
                label="车牌"
            />
            <el-table-column
                prop="driverName"
                label="司机"
            />
            <el-table-column
                show-overflow-tooltip
                prop="currentLocation"
                label="位置"
            />
            <!--          查看实时监控按钮-->
            <el-table-column label="监控" width="80" fixed="right">
              <template #default="{row}">
                <el-icon @click="handleVideoClick(row)" v-if="row && (currentVehicle === row.vehicleNo)">
                  <VideoCameraFilled v-if="videoLink"/>
                  <VideoCamera v-else/>
                </el-icon>
              </template>
            </el-table-column>
          </el-table>

        </div>

        <div class="info-detail"
             v-show="currentVehicle && vehicles && vehicles.find(vehicle => vehicle.vehicleNo === currentVehicle)">
          <b>{{
              currentVehicle
            }}</b><span>当前位于{{
            vehicles?.find(vehicle => vehicle.vehicleNo === currentVehicle)?.currentLocation
          }}</span>
          <div style="display: flex;flex-direction: row;justify-content: space-between;align-items: center">
            <b>{{ routeIndex === 0 ? '最新' : '历史' }}配送单明细</b>
            <div style="display: flex;gap: 8px;align-items: center;" v-if="routeArray.length">
              <el-button
                  type="text"
                  @click="routeIndex = Math.max(routeIndex - 1, 0)"
                  :disabled="routeIndex === 0">
                <el-icon>
                  <ArrowLeft/>
                </el-icon>
              </el-button>
              <span>{{ routeIndex + 1 }}/{{ routeArray.length }}</span>
              <el-button
                  type="text"
                  @click="routeIndex = Math.min(routeIndex + 1, routeArray.length - 1)"
                  :disabled="routeIndex === routeArray.length - 1">
                <el-icon>
                  <ArrowRight/>
                </el-icon>
              </el-button>
            </div>
          </div>
          <span>订单{{ currentRoute?.deliveryOrderNo }}</span>
          <el-timeline v-if="currentRoute">
            <el-timeline-item
                v-if="currentRoute?.route"
                v-for="(route, index) in currentRoute?.route??[]"
                :key="index"
                :timestamp="new Date(route?.generatedDate).toLocaleString()"
                placement="top"
            >
              <b>{{ route.location }}</b>
            </el-timeline-item>
          </el-timeline>
          <div v-else>
            <el-alert
                title="未找到相关配送单明细"
                type="info"
                description="当前车辆暂无配送数据"
                :closable="false"
            />
          </div>
        </div>
      </div>
      <div class="video-container" :class="{'visible': videoLink}">
        <video :src="videoLink" controls>
        </video>
        <div>
          <el-icon @click="videoLink = ''">
            <CircleCloseFilled/>
          </el-icon>
        </div>
      </div>
    </div>
    <div class="map-container">
      <BMap
          v-bind="$attrs"
          ak="bOCY81ir4Y7BewkkoAzxTV62JgzjBEA2"
          height="100%"
          :tilt="36"
          :center="center"
          :zoom="zoom"
          :minZoom="3"
          :mapType="type"
          :enableDragging="mapSetting.enableDragging"
          :enableInertialDragging="mapSetting.enableInertialDragging"
          :enableScrollWheelZoom="mapSetting.enableScrollWheelZoom"
          :enableContinuousZoom="mapSetting.enableContinuousZoom"
          :enableDoubleClickZoom="mapSetting.enableDoubleClickZoom"
          :enableKeyboard="mapSetting.enableKeyboard"
          :enablePinchToZoom="mapSetting.enablePinchToZoom"
          :enableTraffic="mapSetting.enableTraffic"
      >
        <!-- 动态渲染标记点 -->
        <BMarker
            v-for="(vehicle, index) in vehicles"
            :key="index"
            :position="{ lng: vehicle.longitude, lat: vehicle.latitude }"
            @click="handleVehicleClick(vehicle)"
            :icon="{ imageUrl: currentVehicle === vehicle.vehicleNo ? mapIconFocus : mapIcon,
                    size: {width: 50, height: 45}}"
        />

        <BPolyline
            v-if="currentRouteLL?.length > 0"
            :path="currentRouteLL"
            :strokeColor="routeIndex > 0 ? 'blue' : 'red'"
            :strokeWeight="3"
            :strokeOpacity="0.5"
        />
      </BMap>
    </div>
  </div>
</template>

<script setup>
import {onMounted, ref} from 'vue';
import {BMap, BMarker, BPolyline} from 'vue3-baidu-map-gl';
import mapIcon from './vehicle_icon.png';
import mapIconFocus from './vehicle_icon_focus.png';
import {getVehicleLocation} from '@/api/delivery/car.js';
import {
  ArrowLeft,
  ArrowRight,
  CircleCloseFilled,
  Search,
  VideoCamera,
  VideoCameraFilled
} from "@element-plus/icons-vue";
import {getLogisticsHistoryByVehicle} from "@/api/delivery/delivery.js";

// 地图中心与缩放级别
const center = ref({lng: 110, lat: 50});
const zoom = ref(7);

// 地图设置
const type = ref('BMAP_NORMAL_MAP');
const mapSetting = ref({
  enableDragging: true,
  enableInertialDragging: true,
  enableScrollWheelZoom: true,
  enableContinuousZoom: true,
  enableDoubleClickZoom: false,
  enableKeyboard: true,
  enablePinchToZoom: true,
  enableTraffic: false,
});

const videoLink = ref('');

const originVehicles = ref([]);
// 车辆数据
const vehicles = ref([]);

const currentVehicle = ref(null);

const routeArray = ref([]);
const routeIndex = ref(0);

const currentRoute = computed(() => {
  console.log(routeArray.value[routeIndex.value]);
  return routeArray.value[routeIndex.value];
});
const currentRouteLL = computed(() => {
  return routeArray.value[routeIndex.value]?.route?.map((item) => {
    return {lng: item.longitude, lat: item.latitude};
  });
});

const handleVideoClick = (vehicle) => {
  if (videoLink.value) {
    videoLink.value = '';
  } else {
    videoLink.value = `https://www.w3school.com.cn/example/html5/mov_bbb.mp4`;
  }
};

watch(currentVehicle, (newVehicle) => {
  routeIndex.value = 0;
  if (newVehicle) {
    getLogisticsHistoryByVehicle(newVehicle)
        .then((res) => {
          if (res?.length > 0) {
            console.log(res)
            //以deliveryOrderNo分组,为[{deliveryOrderNo:String,route:[]}]
            routeArray.value = res.reduce((acc, cur) => {
              const index = acc.findIndex((item) => item.deliveryOrderNo === cur.deliveryOrderNo);
              if (index === -1) {
                acc.push({deliveryOrderNo: cur.deliveryOrderNo, route: [cur]});
              } else {
                acc[index].route.push(cur);
              }
              return acc;
            }, []);
            //按照route中首个元素的generatedDate排序，近期的在前
            routeArray.value.sort((a, b) => {
              return new Date(b.route[0].generatedDate) - new Date(a.route[0].generatedDate);
            });

            routeArray.value.forEach((item, index) => {
              item.route.sort((a, b) => {
                return new Date(b.generatedDate) - new Date(a.generatedDate);
              });
            });

            routeArray.value = routeArray.value.filter((item) => item.route.length > 0);

            console.log(routeArray.value);
          } else {
            console.warn('未获取到有效数据');
            routeArray.value = [];
          }
        })
        .catch((error) => {
          console.error('网络请求失败:', error);
        });
  } else {
    routeArray.value = [];
  }
});

const tableRowClassName = ({
                             row,
                             rowIndex,
                           }) => {
  if (row.vehicleNo === currentVehicle.value) {
    return 'focus-row';
  }
  return ''
}


const handleVehicleClick = (vehicle) => {
  currentVehicle.value = vehicle.vehicleNo;
  center.value = {
    lng: vehicle.longitude,
    lat: vehicle.latitude,
  };
  nextTick(() => {
    const el = document.querySelector('.el-table .focus-row');
    if (el) {
      el.scrollIntoView({behavior: 'smooth', block: 'center'});
    }
  });

};

const filterSearch = (newSearch) => {
  if (!newSearch) {
    newSearch = search.value;
  }

  if (!newSearch || newSearch === '') {
    vehicles.value = originVehicles.value;
  } else {
    vehicles.value = originVehicles.value.filter((vehicle) => {
      return vehicle.vehicleNo.includes(newSearch) ||
          vehicle.currentLocation.includes(newSearch) ||
          vehicle.driverName.includes(newSearch);
    });
  }


  // 更新地图中心到所有车辆的平均位置
  if (vehicles.value.length > 0) {
    const avgLongitude =
        vehicles.value.reduce((sum, vehicle) => sum + (vehicle.longitude || 0), 0) /
        vehicles.value.length;
    const avgLatitude =
        vehicles.value.reduce((sum, vehicle) => sum + (vehicle.latitude || 0), 0) /
        vehicles.value.length;
    center.value = {
      lng: avgLongitude,
      lat: avgLatitude,
    };
  }
}

// 搜索关键字
const search = ref('');

// 监听搜索关键字变化
watch(search, (newSearch) => {
  filterSearch(newSearch)
});

onMounted(() => {


  // 获取车辆位置信息
  getVehicleLocation()
      .then((res) => {
        if (res) {
          // 更新车辆数据
          originVehicles.value = res.data;
          filterSearch()


        } else {
          console.error(res ? res.message : '未获取到有效数据');
        }
      })
      .catch((error) => {
        console.error('网络请求失败:', error);
      });
});
</script>

<style scoped>
.two-container {
  display: flex; /* 使用 Flexbox 布局 */
  flex-direction: row; /* 设置为水平方向排列 */
  gap: 0; /* 设置两列之间的间距 */
  height: calc(100vh - 84px); /* 设置最大高度 */
}

.two-info-container {
  width: calc(100% - 40px);
  position: absolute;
  top: 20px;
  left: 20px;
  bottom: 20px;
  z-index: 1000;
  display: flex;
  pointer-events: none;
}

.two-info-container >* {
  pointer-events: auto;
}

.video-container {
  width: 70%;
  padding-left: 20px;
  transform-origin: left;
  transform: scaleX(0);
  transition: transform 0.5s;
}

.video-container.visible {
  transform: scaleX(1);
  transition: transform 1s;

}

.video-container > div{
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1000;
  cursor: pointer;
  filter: drop-shadow(2px 2px 2px #0000004c);
  opacity: 0.7;
}

.video-container > div:hover{
  opacity: 1;
}


.video-container .el-icon{
  width: 48px;
  height: 48px;
}

.video-container svg{
  width: 32px;
  height: 32px;
}

.video-container:deep(path){
  fill: #fff;
}

.video-container > video {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 16px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #f0f0f0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  transition: height 0.3s;
  position: relative;
  z-index: 1000;
}

.info-container {
  width: 30%;
  display: flex;
  flex-direction: column;
}

.info-search {
  padding: 8px 8px 8px 16px;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  text-align: center;
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  text-overflow: ellipsis;
  line-height: 1.5;
  transition: height 0.3s;
  display: flex;
  align-items: center;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.info-table {
  margin-top: 5px;
  height: 360px;
  border-radius: 16px;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.info-detail {
  padding: 16px;
  background-color: rgba(255, 255, 255, 0.78);
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  border-radius: 16px;
  margin-top: 5px;
  text-align: left;
  font-size: 14px;
  color: #666;
  white-space: wrap;
  line-height: 1.5;
  transition: height 0.3s;
  word-wrap: anywhere;
  overflow: hidden;
  flex: 1;
  display: flex;
  flex-direction: column;
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}


.map-container {
  width: 100%; /* 根据需要调整宽度 */
  height: 100%;
}

.el-input:deep(.el-input__wrapper) {
  box-shadow: none;
}

.el-timeline {
  overflow-y: auto;
}


</style>
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-table .focus-row {
  --el-table-tr-bg-color: var(--el-color-primary-light-9);
}
</style>